//
//  DMPictureView.swift
//  DM_新浪微博
//
//  Created by Damon.JiAo on 16/3/2.
//  Copyright © 2016年 Demon_JiAo. All rights reserved.
//

import UIKit
import SDWebImage


let ItemMargin:CGFloat = 6
let ItemWH = (KUIScreenWidth - 4 * ItemMargin)/3

class DMPictureView: UICollectionView,UICollectionViewDataSource {

    /// 定义配图定义数据
    var pictureViewModel:DMHomeViewCellModel?{
     /** 此方法经常使用，每次赋值结束之后就会调用此方法 */
        didSet{
            
            self.snp_updateConstraints { (make) -> Void in
                
                let size = self.calPictureSize()
                make.width.equalTo(size.width)
                make.height.equalTo(size.height)
                
            }
            /// 设置完之后更新数据
            reloadData()
        }
    }
    
    //  更改配图的约束
    var pictureList:[DMPictureViewModel]?{
        
        didSet{
            
            self.snp_updateConstraints { (make) -> Void in
                let size = self.calPictureSize()
                make.width.equalTo(size.width)
                make.height.equalTo(size.height)
            }
            reloadData()
        }
        
    }
    
    
    // 刚才我把lazy去掉,就没有报错了? 原因是init 初始化的时候会检测前面flowLayout的实例化
    var flowLayout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        //设置流水布局
        super.init(frame: frame, collectionViewLayout:flowLayout)
        
        self.backgroundColor = UIColor.whiteColor()
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //  加载每一个cell里面的子控件的/约束
    private func setupUI(){
        //  设置数据源代理
        self.dataSource = self
        
        /// 注册cell
        self.registerClass(DMPictureViewCollectionCell.self, forCellWithReuseIdentifier: "itemCell")
        
//        flowLayout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        
        flowLayout.itemSize = CGSizeMake(ItemWH , ItemWH )
        flowLayout.minimumInteritemSpacing = ItemMargin
        flowLayout.minimumLineSpacing = ItemMargin
        
    }

    override func layoutSubviews() {
        super.layoutSubviews()
    }
    
    /*
     * 因为是配图的约束设置问题：
     * 问题来了：选择用什么东西
     * collectionView中每一个cell（item）
     * 显示的内容应该表现在每一个cell里面
    */
    
    /** 1.先设置每一个配图视图的宽高 */
    private func calPictureSize() ->CGSize{
        
        let count = pictureList?.count
        
        if count <= 3{
            return CGSizeMake(ItemWH * 3 + 2 * ItemMargin, ItemWH)
        }else if count == 4{
            
            return CGSizeMake(ItemWH * 2 + ItemMargin, ItemWH * 2 + ItemMargin)
        }else if count == 5||count == 6{
            
            
            return CGSizeMake(ItemWH * 3 + 2 * ItemMargin, ItemWH * 2 + ItemMargin)
//            let row = CGFloat((count! - 1)/3 + 1)
//            
//            return CGSizeMake(KUIScreenWidth - 2 * ItemMargin, (ItemWH + ItemMargin) * row)
        }else {
            return CGSizeMake(ItemWH * 3 + 2 * ItemMargin, ItemWH * 3 + 2 * ItemMargin)
        }
        
    }
    
    
}

extension DMPictureView{
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
//        return pictureViewModel?.cellModel?.pic_urls?.count ?? 0
        return pictureList?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("itemCell", forIndexPath: indexPath) as!DMPictureViewCollectionCell
        
//        let viewModel = DMPictureViewModel()
//        
//        viewModel.model = pictureViewModel?.cellModel?.pic_urls?[indexPath.item]
        
        cell.pictureViewModel = pictureList![indexPath.item]
        
        return cell
    }
    
}

class DMPictureViewCollectionCell:UICollectionViewCell {
    
    var pictureViewModel:DMPictureViewModel?{
        
        didSet{
            
            let url = NSURL(string: pictureViewModel?.model?.thumbnail_pic ?? "")
            
            if let Ourl = url{
              
                iconImageView.sd_setImageWithURL(Ourl)
                
            }
            
        }
        
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setUpInfo()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setUpInfo(){
        
        addSubview(iconImageView)
        
        iconImageView.frame = self.bounds
        
    }
    
    private lazy var iconImageView:UIImageView = {
    
        let img = UIImageView()
        
    return img
    }()
    
}
